// 封装tippy提示指令
import tippy, { Props, Instance } from "tippy.js";
import "tippy.js/dist/tippy.css";
import "tippy.js/themes/light.css";
import "tippy.js/themes/light-border.css";
import "tippy.js/animations/scale.css";
import "tippy.js/animations/scale-extreme.css";
import "tippy.js/animations/shift-away.css";

// 扩展 Element 类型以支持 _tippy 属性
declare global {
  interface Element {
    _tippy?: Instance;
  }
}

// 创建 tips
function createdTips(el: Element, binding: { value: Props }) {
  if (!binding.value.content) {
    // 删除 class 并销毁 tip
    removeTips(el);
    return false;
  }

  // 添加 data-tips class
  el.classList.add("data-tips");

  const defaultConfigProps = {
    animation: "scale-extreme",
  };

  // 初始化 tooltip
  tippy(el, { ...defaultConfigProps, ...binding.value });
}

// 销毁 tips
function removeTips(el: Element) {
  if (el._tippy) {
    el._tippy.destroy();
  }
  el.classList.remove("data-tips");
}

// 指令对象
const tips = {
  mounted(el: Element, binding: { value: Props }) {
    createdTips(el, binding);
  },
  updated(el: Element, binding: { value: Props }) {
    createdTips(el, binding);
  },
  unmounted(el: Element) {
    removeTips(el);
  },
};

export default tips;
